<template>
  <div class="bmel-menu">
    <el-menu
      :default-active="activeMenu"
      mode="horizontal"
      @select="handleSelect"
    >
      <template v-for="(item, index) in constantBmRoutes">
        <!-- v-if="!item.path.includes('Bm-help') || !item.path.includes('Bm-tool')" 暂时隐藏帮助和工具 -->
        <el-menu-item
          :style="{
            '--theme': theme,
            background: getActive(index)
          }"
          @click="selectFn(index, item)"
          :index="item.path"
          :key="index.toString()"
          v-if="
            !item.path.includes('Bm-help') && !item.path.includes('Bm-contract') && !item.path.includes('Bm-search') && !item.path.includes('Bm-project')
          "
        >
          <!-- <svg-icon :icon-class="item.meta.icon || ''" /> -->
          {{ item.meta.title }}
        </el-menu-item>
      </template>
      <!-- 阿米巴预算 -->
      <el-menu-item
        :style="{
          '--theme': theme,
          background: getActive(22)
        }"
        index="22"
        @click="goTool(22)"
      >
        阿米巴预算
      </el-menu-item>
      <!-- 阿米巴预算end -->
      <!-- 智慧贷款(秒贷) -->
      <!-- <el-menu-item
        :style="{
          '--theme': theme,
          background: getLoansActive()
        }"
        index="6"
        @click="goTool(6)"
      >
        秒贷
      </el-menu-item> -->
      <!-- 智慧贷款(秒贷) end -->

      <el-menu-item index="123" key="123">
        <el-dropdown>
          <span class="el-dropdown-link">
            <i class="el-icon-more"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              @click.native="moreEvent('/Bm-personalCenter/study')"
              v-show="token"
              ><svg-icon icon-class="xuexi_icon" />学习</el-dropdown-item>
            <el-dropdown-item
              @click.native="moreEvent('/Bm-personalCenter/expertsCert')"
              v-show="token"
              ><svg-icon icon-class="zjrz_icon" />认证</el-dropdown-item>
            <!-- <el-dropdown-item
              v-show="token"
              @click.native="moreEvent('/Bm-personalCenter/myAskAround')"
              ><svg-icon icon-class="zx_icon" />问圈</el-dropdown-item> -->
            <!-- <el-dropdown-item v-show="token" @click.native="goHelp()"
              ><svg-icon icon-class="help_icon" />帮助</el-dropdown-item> -->
            <!-- 行知历 -->
            <!-- <el-dropdown-item v-show="token" @click.native="moreEvent('/Bm-personalCenter/knownAction')"
              ><svg-icon icon-class="date" />行知历</el-dropdown-item> -->
            <!-- 套餐
            <el-dropdown-item
              v-show="token"
              @click.native="moreEvent('')"
              ><svg-icon icon-class="help_icon" />套餐</el-dropdown-item
            > -->
            <!-- <el-dropdown-item @click.native="moreEvent('/Bm-tool/review')"
              >合同智审</el-dropdown-item
            > -->
            <!-- <el-dropdown-item
              @click.native="moreEvent('/Bm-personalCenter/login')"
              >客服</el-dropdown-item
            > -->
          </el-dropdown-menu>
        </el-dropdown>
      </el-menu-item>
      <!-- 顶部菜单超出数量折叠 -->
      <!-- <el-submenu
      :style="{ '--theme': theme }"
      index="more"
      v-if="topMenus.length > visibleNumber"
    >
      <template v-for="(item, index) in topMenus">
        <el-menu-item
          :index="item.path"
          :key="index"
          v-if="index >= visibleNumber"
        >
          {{ item.meta.title }}
        </el-menu-item>
      </template>
    </el-submenu> -->
    </el-menu>
    <!-- <div>出来吧出来</div> -->
  </div>
</template>

<script>
import { bus } from "@/wss/utils/bus.js";
import { constantBmRoutes, personalCenter } from "@/router";
import { mapGetters } from "vuex";
import { getConsultTypeListApi } from "@/wss/newApi_3-24/work/consultType.js";
import { getProjectTypelistApi } from "@/wss/newApi_3-24/work/projectType.js";
export default {
  data() {
    return {
      currentSelect: 0,
      // 顶部栏初始数
      visibleNumber: 8,
      // 是否为首次加载
      isFrist: false,
      // 当前激活菜单的 index
      currentIndex: undefined,
      constantBmRoutes,

      consultList: [], //咨询类型列表
      projectList: [] //项目类型列表
    };
  },
  watch: {
    $route: {
      deep: true,
      handler(route) {
        // 从其他按钮点击保持高亮,后台暂时没有其他按钮跳转
        const path = route.path;
        if (path.startsWith("/Bm-messageCenter")) {
          // /Bm-search 之前是搜搜
          this.currentSelect = 0;
        } else if (path.startsWith("/Bm-myAskAround")) {
          this.currentSelect = 1;
        } else if (path.startsWith("/Bm-Consult")) {
          this.currentSelect = 2;
        } else if (path.startsWith("/Bm-project")) {
          // this.currentSelect = 2;
        } else if (path.startsWith("/Bm-tool")) {
          if(path.includes('budget')){
            // 阿米巴
            this.currentSelect = 22
          }else{
            this.currentSelect = 3;
          }
        } else if (path.startsWith("/Bm-help")) {
          this.currentSelect = 4;
        } else {
          this.currentSelect = "";
        }
      }
    }
  },
  computed: {
    // 判断当前点击的是那个一级菜单，对应的菜单高亮成#f18e1e
    getActive() {
      return index => {
        // currentSelect 一改变就会触发
        return this.currentSelect === index ? "#f18e1e" : "";
      };
    },

    theme() {
      return this.$store.state.settings.theme;
    },
    ...mapGetters([
      "token"

      // ...
    ]),
    // 顶部显示菜单
    topMenus() {
      // console.log("出来出来");
      let topMenus = [];
      this.routers.map(menu => {
        // console.log(menu.name.includes('Bm'));
        if (menu.hidden !== true) {
          // 兼容顶部栏一级菜单内部跳转
          if (menu.path === "/") {
            topMenus.push(menu.children[0]);
          } else {
            topMenus.push(menu);
          }
        }
      });

      return topMenus;
    },
    // 所有的路由信息
    routers() {
      return constantBmRoutes;
    },

    // 默认激活的菜单（点击一级菜单触发）
    activeMenu() {
      const path = this.$route.path;

      // 是前台个人中心时，生成个人中心，然后直接退出
      if (path.startsWith("/Bm-personalCenter")) {
        this.$bus.$emit("AmchangeBackground").$emit("changeBackground");
        // 个人中心菜单
        let personRouter = [
          {
            hidden: false,
            meta: {
              title: "主页",
              icon: "zy_icon_nor",
              icon2: "zy_icon_sel"
            },
            parentPath: "",
            component: () =>
              import("@/BMViews/views/userCenter/homepage/index.vue"),
            // component: require([`@/bmViews-userCenter/homepage`], resolve),
            path: "/Bm-personalCenter/homepage",
            parentPath: "/Bm-personalCenter"
          },
          {
            hidden: false,
            parentPath: "/Bm-personalCenter",
            meta: {
              icon: "dd_icon_nor",
              icon2: "dd_icon_sel",

              title: "订单"
            },
            path: "/Bm-personalCenter/myOrder",
            component: () =>
              import("@/BMViews/views/userCenter/myOrder/index.vue")
            // component: () => import("/Bm-project/finance"),
          },

          // {
          //   hidden: false,
          //   parentPath: "/Bm-personalCenter",
          //   meta: {
          //     icon: "wq_icon_nor",
          //     icon2: "wq_icon_sel",

          //     title: "问圈",
          //   },
          //   path: "/Bm-personalCenter/myAskAround",
          //   component: () => import("@/BMViews/views/myAskAround/index.vue"),
          //   // component: () => import("/Bm-project/finance"),
          // },
          // {
          //   hidden: false,
          //   meta: {
          //     title: "认证",
          //     icon: "zjrz_icon_nor",
          //     icon2: "zjrz_icon_sel",
          //   },
          //   component: () =>
          //     import("@/BMViews/views/userCenter/expertsCert/index.vue"),
          //   path: "/Bm-personalCenter/expertsCert",
          //   parentPath: "/Bm-personalCenter",
          // },
          {
            hidden: false,
            meta: {
              title: "发票",
              icon: "fpwt_icon_nor",
              icon2: "fpwt_icon_sel"
            },
            component: () =>
              import("@/BMViews/views/userCenter/aboutInvoice/index.vue"),
            path: "/Bm-personalCenter/aboutInvoice",
            parentPath: "/Bm-personalCenter"
          },
          // {
          //   hidden: false,
          //   meta: {
          //     title: "学习",
          //     icon: "xuexi_icon_nor",
          //     icon2: "xuexi_icon_sel",
          //   },
          //   path: "/Bm-personalCenter/study",
          //   parentPath: "/Bm-personalCenter",
          //   component: () =>
          //     import("@/BMViews/views/userCenter/study/index.vue"),
          //   // component: () => import("/Bm-personalCenter/messageCenter"),
          // },
          {
            hidden: false,
            meta: {
              icon: "gy_icon_nor",
              icon2: "gy_icon_sel",
              title: "关于"
            },
            parentPath: "/Bm-personalCenter",
            component: () =>
              import("@/BMViews/views/userCenter/aboutUs/index.vue"),
            path: "/Bm-personalCenter/aboutUs"

            // component: () => import("/bmViews-userCenter/aboutUs"),
          }
        ];
        // 设置个人菜单菜单下的侧边路由
        this.$store.commit("SET_SIDEBAR_ROUTERS", personRouter);
        return;
      }
      let activePath = this.defaultRouter();
      // 判断当前菜单的url
      if (path.lastIndexOf("/") > 0) {
        const tmpPath = path.substring(1, path.length);
        activePath = "/" + tmpPath.substring(0, tmpPath.indexOf("/"));
      } else if ("/index" == path || "" == path) {
        if (!this.isFrist) {
          this.isFrist = true;
        } else {
          activePath = "index";
        }
      }
      // 不是前台时，直接退出
      if (!path.startsWith("/Bm")) return;
      var routes = this.activeRoutes(activePath);

      if (routes.length === 0) {
        activePath = this.currentIndex || this.defaultRouter();
        this.activeRoutes(activePath);
      }
      return activePath;
    }
  },
  beforeMount() {
    window.addEventListener("resize", this.setVisibleNumber);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.setVisibleNumber);
  },

  mounted() {
    //监听后台台是否点击了，点击了就干掉前台一级菜单高亮
    this.$bus.$on("AmchangeBackground", e => {
      this.currentSelect = "";
    });
    const path = this.$route.path;
    // 刷新保持高亮 如果当前url再搜搜下面就让搜搜保持高亮，搜搜的索引是0以此类推
    if (path.startsWith("/Bm-messageCenter")) {
      // /Bm-search 之前是搜搜
      this.currentSelect = 0;
    } else if (path.startsWith("/Bm-myAskAround")) {
      this.currentSelect = 1;
    }else if (path.startsWith("/Bm-Consult")) {
      this.currentSelect = 2;
    } else if (path.startsWith("/Bm-project")) {
      // this.currentSelect = 2;
    } else if (path.startsWith("/Bm-tool")) {
      if(path.includes('budget')){
        // 阿米巴
        this.currentSelect = 22
      }else{
        this.currentSelect = 3;
      }
    } else if (path.startsWith("/Bm-help")) {
      this.currentSelect = 4;
    } else {
      this.currentSelect = "";
    }
  },

  methods: {
    // 是否显示三个点
    isShowMoreFun() {
      // if(this.$route.path.includes('myAskAround') || this.$route.path.includes('expertsCert')){
      //   return false
      // }else{
      //   return true
      // }
      let u = navigator.userAgent;
      if (u.includes("Mac OS")) {
        return false;
      } else {
        return true;
      }
    },

    // 获取咨询类型
    async getConsultTypeListFn() {
      let { code, rows } = await getConsultTypeListApi();
      if (code != 200) return;
      this.consultList = rows; //咨询类型列表
    },

    // 获取项目类型
    async getProjectTypeListFn() {
      let { code, rows } = await getProjectTypelistApi();
      if (code != 200) return;
      this.projectList = rows; //项目类型列表
    },

    // 跳转
    moreEvent(path) {
      // console.log(path, "path");
      this.$router.push({
        path
      });
    },
    // 跳转动态路由帮助
    goHelp() {
      let help = this.$router.options.routes.find(item => {
        return item.path.includes("Bm-help");
      });
      this.$router.push({ path: help.children[0].path });
    },

    // 判断是不是 22阿米巴预算
    getBudgetActive() {
      if (this.$route.path.includes("budget")) {
        let navs = document.querySelectorAll('.bmel-menu ul li')
        console.log(navs,'判断是不是 22阿米巴预算');
        return "#f18e1e";
      }
    },
    // 判断是不是 22阿米巴预算 end

    // 判断是不是 6智慧贷款(秒贷)
    getLoansActive() {
      if (this.$route.path.includes("Loans")) {
        return "#f18e1e";
      }
    },
    // 判断是不是 6智慧贷款(秒贷)end

    // 跳转 22阿米巴预算 和 6智慧贷款(秒贷)
    goTool(type) {
      if (type == 22) {
        // 跳转 22阿米巴预算
        this.$router.push({ path: "/Bm-tool/budget" });
      } else if (type == 6) {
        // 跳转 6智慧贷款(秒贷)
        this.$router.push({ path: "/Bm-tool/Loans" });
      }
    },

    // 设置子路由
    childrenMenus() {
      // -----------咨询的子路由-----------
      // let consultIndex = constantBmRoutes.findIndex(
      //   (item) => item.path == "/Bm-Consult"
      // );
      // constantBmRoutes[consultIndex].children = [];
      // console.log(constantBmRoutes, "6666666666666666666666");

      // this.consultList.forEach((item) => {
      //   constantBmRoutes[consultIndex].children.push({
      //     meta: {
      //       icon: "cai_icon_nor",
      //       icon2: "cai_icon_sel",
      //       title: item.name,
      //       id: item.id,
      //     },
      //     path: "/Bm-Consult/" + item.id,
      //     parentPath: "/Bm-Consult",
      //     component: () => import("@/BMViews/views/Consult/finance/index.vue"),
      //   });
      // });

      // console.log(this.consultList, "------------------xxxxxx");
      // -----------咨询的子路由-----------end

      var childrenMenus = [];

      constantBmRoutes.map(router => {
        for (var item in router.children) {
          if (router.children[item].parentPath === undefined) {
            if (router.path === "/") {
              router.children[item].path =
                "/redirect/" + router.children[item].path;
            } else {
              if (!this.ishttp(router.children[item].path)) {
                router.children[item].path =
                  router.path + "/" + router.children[item].path;
              }
            }
            router.children[item].parentPath = router.path;
          }
          childrenMenus.push(router.children[item]);
        }
      });

      return constantBmRoutes.concat(childrenMenus);
    },
    // 点击一级菜单默认跳转与高亮 (去掉后台的高亮)
    selectFn(index, { children }) {
      console.clear();
      console.log(children);
      // 让这个一级菜单下的第一个二级菜单高亮
      children[0].meta.isActive = true;
      // 切换一级菜单时跳转到此一级菜单下的第一个二级菜单
      this.$router.push({
        path: children[0].path
      });

      // 干掉后台菜单
      this.currentSelect = index;
      this.$bus.$emit("changeBackground");
    },
    // 根据宽度计算设置显示栏数
    setVisibleNumber() {
      const width = document.body.getBoundingClientRect().width / 3;
      this.visibleNumber = parseInt(width / 85);
    },
    // 默认激活的路由
    defaultRouter() {
      let router;

      Object.keys(this.routers).some(key => {
        if (!this.routers[key].hidden) {
          router = this.routers[key].path;
          return true;
        }
      });
      return router;
    },
    // 菜单选择事件
    handleSelect(key, keyPath) {
      this.currentIndex = key;

      if (this.ishttp(key)) {
        // http(s):// 路径新窗口打开
        window.open(key, "_blank");
      } else if (key.indexOf("/redirect") !== -1) {
        // /redirect 路径内部打开
        this.$router.push({ path: key.replace("/redirect", "") });
      } else {
        // 显示左侧联动菜单
        this.activeRoutes(key);
      }
    },
    // 过滤出一级菜单下的二级菜单
    activeRoutes(key) {
      var routes = [];
      if (this.childrenMenus() && this.childrenMenus().length > 0) {
        this.childrenMenus().map(item => {
          if (key == item.parentPath || (key == "index" && "" == item.path)) {
            routes.push(item);
          }
        });
      }
      if (routes.length > 0) {
        routes.find(item => {
          if (Object.is(item.path, this.$route.path)) item.meta.isActive = true;
        });

        if (key == undefined) return;
        // 动态设置二级菜单
        this.$store.commit("SET_SIDEBAR_ROUTERS", routes);
      }
      return routes;
    },
    ishttp(url) {
      return url.indexOf("http://") !== -1 || url.indexOf("https://") !== -1;
    }
  }
};
</script>
<style lang="scss" scoped>
.bmel-menu {
  // width: calc(100% - 230px);
  margin-left: 15px;
}
::v-deep .el-menu {
  background-color: #19244c;
  display: flex;
  align-items: center;
}
::v-deep .el-menu > .el-menu-item:hover {
  background-color: #f18e1e;

  color: #fff;
}
::v-deep .el-menu.el-menu--horizontal {
  border-bottom: unset !important;
}
.el-icon-more {
  color: #fff;
}
::v-deep .el-menu > .el-menu-item.is-active,
::v-deep .el-menu > .el-submenu.is-active .el-submenu__title {
  // border-bottom: 2px solid #{"var(--theme)"} !important;
  color: #303133;
}
// ::v-deep .el-menu > .el-menu-item.is-active {
//   background-color: #f18e1e;
//   border-bottom: unset !important;
//   color: #fff;
// }
::v-deep .el-dropdown {
  color: #fff;
}
::v-deep .el-menu > .el-menu-item {
  margin-right: 16px;
  // width: 70px;
  display: inline-block;
  padding: 0px 15px;
  color: #fff;
  // height: 34px;
  // height: 60px;
  text-align: center;
  border-radius: 20px;
  height: 32px;
  line-height: 32px;
  text-align: center;
  font-size: 16px;
  font-family: PingFangSC-Semibold, PingFang SC;
  font-weight: 600;
  color: #ffffff;
  border-bottom: unset !important;
}
::v-deep .el-menu > .el-menu-item:hover,
::v-deep .el-menu > .el-menu-item.is-active {
  border-bottom: unset;
  color: #ffffff;
  // color: #409eff !important;
  // background-color: #f18e1e;
}

/* submenu item */
::v-deep .el-menu > .el-submenu .el-submenu__title {
  float: left;
  height: 50px !important;
  line-height: 50px !important;
  color: #999093 !important;
  padding: 0 5px !important;
  margin: 0 10px !important;
}
::v-deep .el-menu > .el-submenu .el-submenu__title:hover {
  background-color: transparent;
}
::v-deep .el-menu-item {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #9ba8c4;
}

.el-dropdown-menu--medium .el-dropdown-menu__item {
  display: flex;
  align-items: center;
  padding-top: 5px;
  padding-bottom: 5px;
  border-bottom: 1px solid #f5f5f5;
}
.el-dropdown-menu--medium .el-dropdown-menu__item svg {
  margin-right: 5px;
}
.el-dropdown-menu--medium .el-dropdown-menu__item:last-child {
  border-bottom: 0;
}

@media (max-width: 1120px) {
  ::v-deep .el-menu > .el-menu-item {
    margin-right: 6px;
  }
}
</style>
<style>
.bmel-menu .el-menu--horizontal > .el-menu-item:not(.is-disabled):hover,
.bmel-menu .el-menu--horizontal > .el-menu-item:not(.is-disabled):focus {
  color: #ffffff;
}
</style>
